package sctu.edu.java.year2016.team01.xuhanmei.day20160611;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2016/6/12..
 */
public class MyTCP {
    private BufferedReader reader;
    private ServerSocket server;
    private Socket socket;


    void getserver() {
        try {
            server = new ServerSocket(9898);
            System.out.println("服务器套接字已经创建成功");
            while (true) {
                System.out.println("等待客户机连接");
                socket = server.accept();
                reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                getClientMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public void getClientMessage() {
        try {
            while (true) {//如果套接字是连接状态
                System.out.println("客户机：" + reader.readLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (reader != null) {
                reader.close();//关闭流
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (socket != null) {
                socket.close();//关闭套接字
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) {
        MyTCP tcp = new MyTCP();
        tcp.getserver();//调用方法
    }
}
